package com.readbooker.website.util;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {
  /**
   * 设置Cookie
   * @param response
   * @param value
   */
  public static void addCookie(HttpServletResponse response, String name , String value,int maxAge) {
    Cookie cookie = new Cookie(name,value);
    cookie.setPath("/");
    if(maxAge > 0) {
      cookie.setMaxAge(maxAge);  //退出页面 cookie 默认值-1
    }
    response.addCookie(cookie);
  }

  /**
   * 根据名字获取cookie
   * @param name
   * @return
   */
  public static Cookie getCookieByName(HttpServletRequest request,String name) {
    Map<String,Cookie> cookieMap = ReadCookieMap(request);
    if(cookieMap.containsKey(name)) {
      Cookie cookie = cookieMap.get(name);
      return cookie;
    }else {
      return null;
    }
  }

  /**
   * 将cookie封装到map里面
   * @param request
   * @return
   */
  private static Map<String, Cookie> ReadCookieMap(HttpServletRequest request) {
    Map<String , Cookie> cookieMap = new HashMap<String , Cookie>();
    Cookie[] cookies = request.getCookies();
    if(null != cookies) {
      for(Cookie cookie : cookies) {
        cookieMap.put(cookie.getName(), cookie);
      }
    }
    return cookieMap;
  }

}
